<template>
  <div class="table-box" v-loading="loading">
    <ProTable
      ref="proTable"
      title="门禁点列表"
      rowKey="doorsn"
      :columns="columns"
      :request-api="getTableList"
      :data-callback="dataCallback"
      :tool-button="false"
      :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
      :small="true"
      v-if="columns.length"
    >
      <template #tableHeader="scope">
        <el-button type="primary" text :icon="CopyDocument" @click="_copyAccess">复制权限</el-button>
        <el-button type="primary" text :icon="CirclePlus" @click="_addDoor">增加</el-button>
        <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
    </ProTable>
    <EmployeeDialog
      :empid="props.empid"
      :dialogVisible="dialogVisible1"
      :handleClose="handleClose"
      :submitCallback="_submitEmp"
      :empcardTypes="empcardTypes"
      :zNodes="zNodes"
      v-if="zNodes.length"
    />
    <DoorDialog
      :dialogVisible="dialogVisible"
      :areaSelList="areaSelList"
      :empId="props.empid"
      :handleClose="handleClose"
      :submitCallback="_submitDoor"
    />
  </div>
</template>

<script setup lang="tsx" name="roleInfo">
import { ref, onMounted, watch } from "vue";
import { CopyDocument, CirclePlus, Delete } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import EmployeeDialog from "./EmployeeDialog.vue";
import DoorDialog from "./DoorDialog.vue";
import {
  getDoorList,
  getAreaSelList,
  delDoor,
  getEmpcardTypes,
  copyAccess,
  addDoor
} from "@/api/modules/elevatorControl/empower/cardholder";
import { ElMessage, ElMessageBox } from "element-plus";

const loading = ref(false);
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const areaSelList = ref([]);
const empcardTypes = ref([]);
const proTable = ref();

const columns = ref([]);
const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records,
    total: page.total
  };
};

const getTableList = (params: any) => {
  loading.value = true;
  let newParams = JSON.parse(JSON.stringify(params));
  if (!props.empid) {
    return new Promise(function (resolve) {
      resolve({ data: { page: { total: 0 }, records: [] } });
    });
  } else {
    return getDoorList({
      ...newParams,
      empId: props.empid,
      checkOptDoorRight: true,
      checkArea: true,
      empHasAccess: true,
      doorType: 1
    });
  }
};

const _addDoor = () => {
  if (!props.empid) {
    ElMessage.error("请先选择人员");
    return false;
  }
  dialogVisible.value = true;
};

const _copyAccess = () => {
  if (!props.empid) {
    ElMessage.error("请先选择被复制的人员");
    return false;
  }
  dialogVisible1.value = true;
};

const _submitEmp = async ids => {
  try {
    const res = await copyAccess({ doorType: 1, empIdSrcList: [props.empid], empIdDesList: ids });
    const { v1, v2 } = res.data;
    ElMessage.success(`复制成功：${v1},失败：${v2}`);
    dialogVisible1.value = false;
  } catch (error) {
    console.log(error);
  }
};

const _submitDoor = async ids => {
  try {
    const res = await addDoor({ timeCode: 0, empIds: [props.empid], doorSns: ids });
    const { v1, v2 } = res.data;
    ElMessage.success(`增加成功：${v1},失败：${v2}`);
    dialogVisible.value = false;
    proTable.value.clearSelection();
    proTable.value.reset();
  } catch (error) {
    console.log(error);
  }
};

const _batchDel = async (selectedListIds: string[]) => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择门禁点");
    return false;
  }
  ElMessageBox.confirm(`是否删除所选门禁点?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const res = await delDoor({ empIds: [props.empid], doorSns: selectedListIds });
      const { v1, v2 } = res.data;
      ElMessage.success(`删除成功：${v1},失败：${v2}`);

      proTable.value.clearSelection();
      proTable.value.getTableList();
    } catch (error) {
      console.log(error);
    }
  });
};

const getEmpcardTypeData = async () => {
  try {
    const res = await getEmpcardTypes();
    empcardTypes.value = res.data;
  } catch (error) {
    console.log(error);
  }
};

const getAreaSelData = async () => {
  try {
    const res: any = await getAreaSelList();
    areaSelList.value = res.data;
    areaSelList.value.unshift({
      key: "",
      value: "全部"
    });
    areaSelList.value = areaSelList.value.map(item => {
      return {
        ...item,
        label: item.value,
        value: item.key
      };
    });
    columns.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "areaId",
        label: "区域",
        isShow: false,
        enum: areaSelList.value,
        search: {
          el: "select",
          defaultValue: ""
        }
      },
      {
        prop: "clause",
        label: "描述",
        isShow: false,
        search: {
          el: "input"
        }
      },
      {
        prop: "areaid",
        label: "区域",
        render: scope => {
          return areaSelList.value.find(item => item.key === scope.row.areaid).label;
        },
        minWidth: 200
      },
      {
        prop: "doorsn",
        label: "门禁点编码",
        minWidth: 200
      },
      {
        prop: "doorname",
        label: "门禁点描述",
        minWidth: 200
      }
    ];
  } catch (error) {
    columns.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "clause",
        label: "描述",
        isShow: false,
        search: {
          el: "input"
        }
      },
      {
        prop: "doorsn",
        label: "门禁点编码",
        minWidth: 200
      },
      {
        prop: "doorname",
        label: "门禁点描述",
        minWidth: 200
      }
    ];
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
};

const props = defineProps<{
  empid: string;
  zNodes: { [key: string]: any }[];
}>();

watch(
  () => props.empid,
  () => {
    if (proTable.value) {
      proTable.value.clearSelection();
      proTable.value.reset();
    }
  }
);

onMounted(() => {
  getAreaSelData();
  getEmpcardTypeData();
});
</script>
<style lang="scss" scoped>
.table-box {
  box-sizing: border-box;
  width: 100%;
  height: calc(100% - 50px);
  padding: 10px 0;
  overflow-y: auto;
}
</style>
